import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import ChoosePerson from '@/components/BindPerson/ChoosePerson';
import HasUser from '@/components/BindPerson/HasUser';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Tree,
  Modal,
  Badge,
  Divider,
  Radio,
  Dropdown,
  Icon,
  Menu,
  message,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {ruleP, nameMaxLength,remarkMaxLength} from '@/utils/rule'
import styles from '../search.less';
const {TreeNode} = Tree;
const DirectoryTree = Tree.DirectoryTree;
const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const getValue = obj =>
  Object.keys(obj)
    .map(id => obj[id])
    .join(',');

const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleAdd,
    handleModalVisible ,
    levelTypeList,
    levelTypeValue,
    levelType
  } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };

  const levelTypeOn = (value) => {
    levelType(value);
  }

  return (
    <Modal
      destroyOnClose
      width={640}
      title="新增用户等级"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formLayout} label="名称">
        {form.getFieldDecorator('levelName', {
          rules: [{required: true,message:'名称不能为空'},{max:nameMaxLength()[0],message:nameMaxLength()[1]}],
        })(<Input placeholder="请输入"/>)}
      </FormItem>

      <FormItem {...formLayout} label="类型">
        {form.getFieldDecorator('levelType',{
          rules: [{required: true,message:'请选择类型'}],
        })(
          <Select placeholder="请选择" style={{ width: '100%' }} onChange={levelTypeOn}>
            {
            levelTypeList && levelTypeList.map((item,index) => {
              return (<Option  key={index} value={item.value}>{item.name}</Option>)
            })
          }
          </Select>
        )}
      </FormItem>

      {levelTypeValue&&levelTypeValue.length?<FormItem {...formLayout} label="等级">
              {form.getFieldDecorator('levelScore',{
                rules: [{required: true,message:'请选择等级'}],
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {
                    levelTypeValue && levelTypeValue.map((item,index) => {
                      return (<Option key={index} value={item.value}>{item.name}</Option>)
                    })
                  }
                </Select>
              )}
              <span>提示：职级等级值越小，文件安全管控要求越低。</span>
            </FormItem>:null}

      <FormItem id="remark" {...formLayout} label="备注">
        {form.getFieldDecorator('remark',{rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}]})(<TextArea
          style={{minHeight: 32}}
          rows={2}
        />)}
      </FormItem>
    </Modal>
  );
});

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => {},
    handleUpdateModalVisible: () => {},
    values: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        levelName: props.values.levelName,
        levelTypeName: props.values.levelTypeName,
        levelScore: props.values.levelScore,
        remark: props.values.remark,
        status: props.values.status,
        levelTypeList:[],
        id: props.values.id,
      },
    };
  }

  //编辑，确定提交
  handleCheck = checkBtn => {
    const { form, handleUpdate } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          handleUpdate(formVals);
        }

      );
    });
  };
  renderFooter = checkBtn => {
    const { handleUpdateModalVisible, values } = this.props;
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleCheck(checkBtn)}>
        确定
      </Button>,
    ];
  };

  levelTypeOn = value => {
    const { levelType } = this.props;
    levelType(value);
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values ,form, levelTypeList,levelTypeValue
    } = this.props;
    const { checkBtn, formVals } = this.state;
    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="编辑用户等级"
        visible={updateModalVisible}
        footer={this.renderFooter(checkBtn)}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
        maskClosable={false}
      >

        <FormItem id="levelName" {...formLayout} label="名称">
          {form.getFieldDecorator('levelName', {
            rules: [{required: true,message:'名称不能为空'}],initialValue: values.levelName
          })(<Input placeholder="请输入"/>)}
        </FormItem>

        <FormItem id="levelTypeName" {...formLayout} label="类型">
          {form.getFieldDecorator('levelType',
            {rules: [{required: true,message:'请选择类型'}],
          initialValue: values&&values.levelType})(
            <Select placeholder="请选择" style={{ width: '100%' }} onChange={this.levelTypeOn}>
              {
                levelTypeList && levelTypeList.map((item,index) => {
                  return (<Option  key={index} value={item.value}>{item.name}</Option>)
                })
              }
            </Select>
          )}
        </FormItem>

        {levelTypeValue && levelTypeValue?<FormItem id="levelScore" {...formLayout} label="等级">
                  {form.getFieldDecorator('levelScore',{rules: [{required: true,message:'请选择等级'}],initialValue: formVals.levelScore.toString()})(
                    <Select placeholder="请选择" style={{ width: '100%' }}>
                      {
                        levelTypeValue && levelTypeValue.map((item,index) => {
                          return (<Option key={index} value={item.value}>{item.name}</Option>)
                        })
                      }
                    </Select>
                  )}
          <span>提示：职级等越高，等级值越小，文件安全管控要求越低。</span>
        </FormItem>:null}

        <FormItem id="remark" {...formLayout} label="备注">
          {form.getFieldDecorator('remark', {
            rules:[{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],
            initialValue: values.remark})(<TextArea
            style={{minHeight: 32}}
            rows={2}
          />)}
        </FormItem>

        <FormItem id="status" {...formLayout} label="状态设置">
          {form.getFieldDecorator('status',{initialValue: values.status})(
            <Radio.Group>
              <Radio value={0}>
                启用
              </Radio>
              <Radio value={1}>
                禁用
              </Radio>
            </Radio.Group>
          )}
        </FormItem>

      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ userGrade, loading }) => ({
  userGrade,
  loading: loading.models.userGrade,
}))
@Form.create()
class userGrade extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    levelTypeValue: [],
     //详情
    detailVisible: false,
    detailsData: {},
    bindUserVisible: false, //绑定用户
    treeDataList: [],//组织树
    orgDataList: [],//用户
    userInfo: {},
    groupMember: [], // 设置的全部人员
    // 设置人员相关
    chooseBVisible: false,
    hasUserVisible: false, //已选人员
    hasUserVisible: false,
  };

  columns = [
    {
      title: '名称',
      dataIndex: 'levelName',
    },
    {
      title: '类型',
      dataIndex: 'levelTypeName',
    },
    {
      title: '等级',
      dataIndex: 'levelScore',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.detailHandelVisible(true, record)}>详情</a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</Menu.Item>
                <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
                <Menu.Item onClick={() => this.handChooseBVisible(true, text)}>人员设置</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>

          {/*<a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleThisRowDelete(record)}>删除</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleBindUserVisible(true,text)}>人员设置</a>*/}
        </Fragment>
      ),
    },
  ];

  // h
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userGrade/queryList',
    });
    dispatch({
      type: 'userGrade/levelTypeList',
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({ levelTypeList: res.data.dataList,}
          )
        }
      },
    });

    this.treeData(); // 组织树请求
  }

  listForLevelSF = (levelScore) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userGrade/listForLevelScore',
      payload: {levelScore},
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            groupMember:res.data.dataList
          });
        }
      },
    });
  }

  levelType = (value) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userGrade/levelTypeValue',
      payload: {typeCode:value},
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            levelTypeValue:res.data.dataList
          });
        }
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, id) => {
      const newObj = { ...obj };
      newObj[id] = getValue(filtersArg[id]);
      return newObj;
    }, {});

    const params = {
      pageNum: pagination.current-1,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'userGrade/queryList',
      payload: params,
    });
  };

   // 已选择成员详情弹框
  handleHasUserVisible = (flag) => {
    this.setState({
      hasUserVisible: !!flag,
    });
  };

  deleteGMember = (userCode) => {
    const { groupMember } = this.state;
    let copyGM = [...groupMember];
    copyGM.map((v,i) => {
      if(v.userCode == userCode) {
        copyGM.splice(i,1);
      }
    })
    this.setState({
      groupMember: copyGM,
    })
  }

   // 已选择成员详情弹框
  handChooseBVisible = (flag, userInfo) => {
    this.setState({
      chooseBVisible: !!flag,
      userInfo,
    });
    if(flag) {
      this.listForLevelSF(userInfo.levelScore)
    }
    if(!flag) {
      this.setState({
        groupMember: [],
      })
    }
  };

   // 绑定用户弹框显示和隐藏
  handleBindUserVisible = (flag,selectedRows) => {
    this.setState({
      bindUserVisible: !!flag,
    });
    if(!flag){
      const { groupMember } = this.state;
      const concatArr = selectedRows?groupMember.concat(selectedRows):groupMember;
      // 去重
      const result = [];
      let obj = {};
      for(var i =0; i<concatArr.length; i++){
         if(!obj[concatArr[i].userCode]){
            result.push(concatArr[i]);
            obj[concatArr[i].userCode] = true;
         }
      }
      this.setState({
        // personData: {},
        groupMember: result,
      })
    }
  };

   // 组织树请求
  treeData() {
    const {dispatch} = this.props;
    dispatch({
      type: 'userGrade/getTree',
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            treeDataList:res.data,
          })
        }else {
           Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  //组织人员请求
  getList(res,pageSize=5,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      orgId: res && res.orgId,
      // roleId: res && res.roleId || '',
      userLevel: res && res.userLevel || '',
      pageSize: pageSize,
      pageNum: pageNum,
      userName:res&& res.userName||'',
      userCode:res&& res.userCode||'',
    };
    dispatch({
      type: 'userGrade/getList',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            orgDataList:res.data,
          })
        }else {
           Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

    //绑定人员接口
  bindUserRole(params) {
    const { dispatch } = this.props;
    const value = {
      id: params.roleId,
      userCodeList: params.userCodeList,
    }
    dispatch({
      type: 'userGrade/bindUserRole',
      payload: value,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.handChooseBVisible()
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },
    });
  }

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  handleThisRowDelete = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userGrade/remove',
      payload: {id},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'userGrade/queryList',});
          this.setState({selectedRows: []})
        }else {
         Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'userGrade/queryList',
        payload: values,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
    if(!flag) {
      this.setState({
        levelTypeValue: [],
      })
    }
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      editFormValues: record || {},
    });
    if(!flag) {
      this.setState({
        levelTypeValue: [],
      })
    }
    if(flag) {
      this.levelType(record.levelType)
    }
  };

   detailHandelVisible = (flag,text) => {
    this.setState({
      detailVisible: !!flag,
      detailsData: text,
    });
  };

  //新增
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'userGrade/add',
      payload: {
        levelName: fields.levelName,
        levelType: fields.levelType,
        levelScore: fields.levelScore,
        remark: fields.remark,
        status: fields.status,
      },
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'userGrade/queryList',});
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
    this.handleModalVisible();
  };

  //编辑
  handleUpdate = fields => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'userGrade/update',
      payload: {
        /*query: formValues,*/
        levelName: fields.levelName,
        levelType: fields.levelType,
        // isDefault: fields.isDefault,
        levelScore: fields.levelScore,
        remark: fields.remark,
        status: fields.status,
        id: fields.id,
      },
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'userGrade/queryList',});
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });

    this.handleUpdateModalVisible();
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="名称">
              {getFieldDecorator('levelName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      userGrade: { data },
      loading,
      form,
    } = this.props;
    const { selectedRows, modalVisible, updateModalVisible,editFormValues,
      levelTypeList,levelTypeValue, detailVisible, detailsData,
      bindUserVisible, treeDataList,orgDataList,userInfo,groupMember,chooseBVisible,hasUserVisible,
    } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      levelType: this.levelType,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
      levelType: this.levelType,
    };

    const detailsMethods = {
      detailHandelVisible: this.detailHandelVisible,
    };

    const BindUserMethods = {
      handleBindUserVisible: this.handleBindUserVisible,
      getList: this.getList.bind(this),
      bindUserRole: this.bindUserRole.bind(this),
    }
    const BindChooBMethods = {
      handChooseBVisible: this.handChooseBVisible,
      handleHasUserVisible: this.handleHasUserVisible,
      handleBindUserVisible: this.handleBindUserVisible,
      bindUserRole: this.bindUserRole.bind(this),
    }

    const hasUserMethods = {
      handleHasUserVisible: this.handleHasUserVisible.bind(this),
      deleteGMember: this.deleteGMember.bind(this),
    }

    return (
      <PageHeaderWrapper title="用户分级">
        <Card bordered={false}>
          <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          levelTypeList={levelTypeList}
          levelTypeValue={levelTypeValue}
        />

        {chooseBVisible?<ChooseButton
          {...BindChooBMethods}
          chooseBVisible={chooseBVisible}
          userInfo={userInfo}
          groupMember={groupMember}
        />:null}

        {hasUserVisible?<HasUser
           {...hasUserMethods}
           hasUserVisible={hasUserVisible}
           groupMember={groupMember}
        />:null}

        <ChoosePerson
            {...BindUserMethods}
            bindUserVisible={bindUserVisible}
            treeDataList={treeDataList}
            personData={orgDataList}
            text={userInfo}
          />

         <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
              )}
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              rowKey={record => record.id}
            />
          </div>
          {editFormValues && Object.keys(editFormValues).length ? (
            <UpdateForm
              {...updateMethods}
              updateModalVisible={updateModalVisible}
              values={editFormValues}
              levelTypeList={levelTypeList}
              levelTypeValue={levelTypeValue}
            />
          ) : null}
          {detailsData&&detailsData.id?(
          <Details {...detailsMethods} detailVisible={detailVisible} form={form} detailsData={detailsData} />
        ):null}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

class Details extends PureComponent {
  render() {
    const { detailVisible, detailHandelVisible,detailsData } = this.props;
  return (
    <Modal
      destroyOnClose
      width={800}
      title="查看分级"
      visible={detailVisible}
      onCancel={() => detailHandelVisible()}
      footer={[
        <Button key="back" type="primary" onClick={() => detailHandelVisible()}>返回</Button>
      ]}
      className={styles.viewMore}
    >
      <Row>

        <Col md={12}>
          <FormItem {...formLayout} label="名称">
            {detailsData.levelName}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="类型">
           {detailsData.levelTypeName}
          </FormItem>
        </Col>
        <Col md={12}>
          <FormItem {...formLayout} label="等级">
            {detailsData.levelScore}
          </FormItem>
        </Col>

        <Col md={12}>
          <FormItem {...formLayout} label="状态">
            {detailsData.status==0?'启用':'禁用'}
          </FormItem>
        </Col>
        <Col md={24}>
          <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="备注">
            {detailsData.remark}
          </FormItem>
        </Col>
      </Row>
    </Modal>
  );
  }
}

class ChooseButton extends PureComponent {
  okHandle = () => {
    const {groupMember, userInfo, bindUserRole} = this.props;
    if (!(groupMember.length && groupMember[0].userCode)) {
      message.warning({ content: '请选择设置人员', key: 'peopleChoose' });
      return;
    }
    const userCodeList = groupMember.map((v)=>{return v.userCode}).join(',');
    bindUserRole({roleId:userInfo.id,userCodeList});
  }

  render() {
    const { chooseBVisible, handChooseBVisible, handleHasUserVisible, groupMember, handleBindUserVisible } = this.props;
  return (
    <Modal
      destroyOnClose
      width={800}
      title="人员设置"
      visible={chooseBVisible}
      onCancel={() => handChooseBVisible()}
      onOk={this.okHandle}
      zIndex={999}
    >
      <FormItem labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} label="人员设置">
        <Button type="primary" onClick={() => handleBindUserVisible(true)} >请选择</Button>
        <div>{groupMember&&groupMember.length?groupMember.slice(0,3).map((v,i) => {
        return <span key={i} style={{marginRight:'20px',}}>{v.userName} </span>
      }):null}{groupMember&&groupMember.length&&groupMember.length>3?'...':''}
      {groupMember&&groupMember.length&&groupMember.length>0?<a onClick={() => handleHasUserVisible(true)} style={{marginLeft:25}}>查看已选人员</a>:null}
      </div>
      </FormItem>
    </Modal>
  );
  }
}

export default userGrade;
